package com.example.hrandroidapp.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lib.jason.requestresponsetask.HTTPUtils;
import lib.jason.requestresponsetask.JSONHTTPPoster;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.example.hrandroidapp.OvertimeMailDetailActivity;
import com.example.hrandroidapp.R;
import com.example.hrandroidapp.adapter.OvertimeApprovalAdapter;
import com.example.hrandroidapp.common.Constant;
import com.example.hrandroidapp.common.DateUtils;
import com.example.hrandroidapp.common.HRLog;
import com.example.hrandroidapp.components.ActionsLinearLayout;
import com.example.hrandroidapp.domain.OverTimePO;
import com.example.hrandroidapp.domain.UpdatedOvertimePO;
import com.example.hrandroidapp.preferences.CurrentServerPreference;
import com.example.hrandroidapp.preferences.UserPreference;
import com.google.gson.Gson;

public class OvertimePendingFragment extends Fragment implements OvertimeApprovalAdapter.AcceptCallBack {

	private ListView lstOverTimeAproval;
	private SwipeRefreshLayout swipeLayout;
	private OvertimePendingFragment fragment=this;
	private List<OverTimePO> lstOverTime;
	private static TranslateAnimation anim;

	private OvertimeApprovalAdapter overtimeApprovAdpt;
	private static ActionsLinearLayout actionBar;
	
	private String url=null;
	private String lastOTId = "0";
	private boolean myOT = false;
	
	private final int OPT_APPROVE = 1;
	private final int OPT_REJECT = 2;
	private final String LEAVE_PENDING_STATUS = "1";
	
	private final int PARAM_PENDING = 1;
	private final int PARAM_APPROVE = 2;
	private final int PARAM_REJECT = 3;
	
	private final boolean OT_APPROVE = true;
	
	@Override
	public void onResume() {
		super.onResume();
		loadOvertime();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_overtime_pending, container, false);

		loadViews(rootView);
	    loadOvertime();
		
		actionBar.addActionItem(new ActionsLinearLayout.ActionItem(null, getString(R.string.btn_approve), true,
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        selectChoiceType(OPT_APPROVE);
                    }
                }));
		
        actionBar.addActionItem(new ActionsLinearLayout.ActionItem(null, getString(R.string.btn_reject), true,
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        selectChoiceType(OPT_REJECT);
                    }
                }));
        actionBar.drawActionBar();
		
	    swipeLayout.setOnRefreshListener(new OnRefresh());
	    swipeLayout.setColorScheme(android.R.color.holo_blue_bright, 
	            android.R.color.holo_green_light, 
	            android.R.color.holo_orange_light, 
	            android.R.color.holo_red_light);
		
	    
	    lstOverTimeAproval.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				OverTimePO overtimePO = lstOverTime.get(position); 
				Intent intent = new Intent(fragment.getActivity().getApplicationContext(), OvertimeMailDetailActivity.class);
				intent.putExtra("ot", overtimePO);
				intent.putExtra("pending", "1");
				getActivity().startActivity(intent); 
			}
		});
	    
		return rootView;
	}
	
	private void loadOvertime() {
		if(isAdded()) {
			url = getResources().getString(R.string.overtime_url);
			String completeUrl = "http://" + CurrentServerPreference.getCurrentServer(getActivity()).getSvrIP() + ":" + Constant.PORT + url;
			
			HRLog.postLogInfo("leave pending url complete: " + completeUrl, "LeavePendingFragment.loadLeaves"); 
			
			new HTTPUtils(getActivity(), JSONHTTPPoster.MEDIA_FORM_URLENCODED, completeUrl, populateRequestParameterString(), 
					new HTTPUtils.SimpleRequestResponseTaskInterface() {
	
				@Override
				public void handleResponse(String responseStr, int status) throws Exception {
					JSONArray jsonArray = new JSONArray(responseStr);
					lstOverTime.clear();
					for (int i = 0; i < jsonArray.length(); i++) {
	
		                JSONObject jsonobject = jsonArray.getJSONObject(i);
		                OverTimePO overTimePO = new OverTimePO();
	
		                overTimePO.setOtID(Integer.parseInt(jsonobject.getString("otId")));
		                overTimePO.setEmployeeName(jsonobject.getString("employeeName"));
		                overTimePO.setReason(jsonobject.getString("reason"));
		                overTimePO.setOtDate(DateUtils.getJavaDate(jsonobject.getString("otDate"))); 
		                overTimePO.setTask(jsonobject.getString("task"));
		                overTimePO.setOtMinutes(Integer.parseInt(jsonobject.getString("otMinutes")));
		                overTimePO.setOtType(Integer.parseInt(jsonobject.getString("otType")));
		                lstOverTime.add(overTimePO); 
		            }
					
					Collections.sort(lstOverTime, new Comparator<OverTimePO>() {
	
						@Override
						public int compare(OverTimePO obj1, OverTimePO obj2) {
							return obj2.getOtDate().compareTo(obj1.getOtDate());
						}
					});
					
					overtimeApprovAdpt = new OvertimeApprovalAdapter(fragment.getActivity().getApplicationContext(), lstOverTime, fragment);
				    lstOverTimeAproval.setAdapter(overtimeApprovAdpt);
					
					HRLog.postLogDebug("JSON string: " + responseStr, "LeavePendingFragment.onCreateView");
				}
				
			}).execute();
		}
	}

	private class OnRefresh implements OnRefreshListener {

		@Override
		public void onRefresh() {
			new Handler().postDelayed(new Runnable() {
		        @Override public void run() {
		            swipeLayout.setRefreshing(false);
		        }
		    }, 5000);
		}
	}

	private void loadViews(View rootView) {
		lstOverTimeAproval = (ListView) rootView.findViewById(R.id.ot_list);
		lstOverTime = new ArrayList<OverTimePO>();
		actionBar = (ActionsLinearLayout) rootView.findViewById(R.id.viewGroup_ot_actionBar);
		swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.ot_swipe_container);
	}

	@Override
	public void setAccptVisible(boolean flag) {
		if(flag){
			actionBar.setVisibility(View.GONE); 
		}else {
			actionBar.setVisibility(View.VISIBLE); 
		}
	}

	private void selectChoiceType(int option) {
		List<UpdatedOvertimePO> applyLstOT = new ArrayList<UpdatedOvertimePO>();
		if(option == 1) {			// approve
			List<OverTimePO> lstOvertime = overtimeApprovAdpt.getAllItems();
			List<OverTimePO> newLstOvertime = new ArrayList<OverTimePO>();
			
			actionBar.setVisibility(View.GONE);
			for(int i=0; i<lstOvertime.size(); i++) {
				if(!lstOvertime.get(i).isCheck()) {
					newLstOvertime.add(lstOvertime.get(i));
				}else {
					// send check mails to api
					UpdatedOvertimePO updatedOTPO = new UpdatedOvertimePO(actionBar.getLeaveCommment(), lstOvertime.get(i).getOtID());
					applyLstOT.add(updatedOTPO);
				}
			}
			
			approveRejectOverTimeAPI(applyLstOT, OT_APPROVE);
			overtimeApprovAdpt = new OvertimeApprovalAdapter(getActivity().getApplicationContext(), newLstOvertime, fragment);
			lstOverTimeAproval.setAdapter(overtimeApprovAdpt);
		}else if(option == 2) {			// reject
			List<OverTimePO> lstOvertime = overtimeApprovAdpt.getAllItems();
			List<OverTimePO> newLstOvertime = new ArrayList<OverTimePO>();
			
			actionBar.setVisibility(View.GONE);
			for(int i=0; i<lstOvertime.size(); i++) {
				if(!lstOvertime.get(i).isCheck()) {
					newLstOvertime.add(lstOvertime.get(i));
				}else {
					// send check mails to api
					UpdatedOvertimePO updatedOvertimePO = new UpdatedOvertimePO(actionBar.getLeaveCommment(), lstOvertime.get(i).getOtID());
					applyLstOT.add(updatedOvertimePO); 
				}
			}
			
			approveRejectOverTimeAPI(applyLstOT, !OT_APPROVE);
			overtimeApprovAdpt = new OvertimeApprovalAdapter(getActivity().getApplicationContext(), newLstOvertime, fragment);
		    lstOverTimeAproval.setAdapter(overtimeApprovAdpt);
		}
	}
	
	private void approveRejectOverTimeAPI(List<UpdatedOvertimePO> lstUpdatedOT, boolean status) {
		url = getResources().getString(R.string.overtime_approve_url);
		String completeUrl = "http://" + CurrentServerPreference.getCurrentServer(getActivity()).getSvrIP() + ":" + Constant.PORT + url;
		
		String updateOTArr = new Gson().toJson(lstUpdatedOT);
		
		JSONObject approvedData = new JSONObject();
		try {
			approvedData.put("approved", status);
			approvedData.put("dataList", new JSONArray(updateOTArr)); 
			approvedData.put("loginId", UserPreference.getLoginId(getActivity()));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		HRLog.postLogInfo("overtime approve/reject complete( " + status + "): " + completeUrl, "OvertimePendingFragment.loadOvertime");
		
		new HTTPUtils(getActivity(), JSONHTTPPoster.MEDIA_JSON_TYPE, completeUrl, 
				approvedData.toString(), new HTTPUtils.SimpleRequestResponseTaskInterface() {
					
					@Override
					public void handleResponse(String response, int status) throws Exception {
						if(status == 200) {
							Toast.makeText(getActivity(), "Overtime process successful...", Toast.LENGTH_LONG);
						}else {
							Toast.makeText(getActivity(), "Fail to process Overtime process!!!", Toast.LENGTH_LONG);
						}
					}
				}).execute();
	}

	public Map<String, String> populateRequestParameterString() {
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("overtimeStatus", LEAVE_PENDING_STATUS);
		paramMap.put("overtimeId", lastOTId);
		paramMap.put("loginId", UserPreference.getLoginId(getActivity()));
		paramMap.put("size", String.valueOf(Constant.OVERTIME_SIZE));
		paramMap.put("myOvertime", String.valueOf(myOT));
		return paramMap;
	}
	
}
